//
//  YZEHomeClickViewController.m
//  yilutongxing
//
//  Created by ios-21 on 17/4/9.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import <QMUITips.h>
#import "YZEHomeClickViewController.h"
#import "YZEArticleModel.h"
#import "YZEHomeUtils.h"
#import "YYText.h"

#define LeftItemLength ((40/600.0)*self.view.frame.size.width)
#define RightItemLength ((65/600.0)*self.view.frame.size.width)

#define View_X 20
#define View_Y 30
#define LineSpacing 9
#define TitleLableFont 17

#define URL_Fav @"/api/lore-collections"

@interface YZEHomeClickViewController ()<UIScrollViewDelegate,UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *myScrollView;

@property (strong, nonatomic) UIView *underNavigationView;
@property (strong, nonatomic) UILabel *titleLable;
@property (strong, nonatomic) UILabel *dateLable;
@property (strong, nonatomic) UIImageView *imgView;
@property (strong, nonatomic) UIWebView *contentWebView;
@property (nonatomic,copy)NSString *ID;
@property (nonatomic) NSDictionary *dic;

@end

@implementation YZEHomeClickViewController

-(void)loadControls{
    self.underNavigationView = [UIView new];
    self.titleLable = [UILabel new];
    self.dateLable = [UILabel new];
    self.imgView = [UIImageView new];
    self.contentWebView = [UIWebView new];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y <= 0) {
        CGPoint conOffset = scrollView.contentOffset;
        conOffset.y = 0;
        scrollView.contentOffset = conOffset;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.myScrollView.delegate = self;
    
    [self loadControls];
    self.myScrollView.showsVerticalScrollIndicator = NO;
    CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
    CGRect rectNav = self.navigationController.navigationBar.frame;
    self.myScrollView.frame = CGRectMake(0, rectStatus.size.height+rectNav.size.height, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    
    [self setTitleViewAlignment];
    //换掉背景图
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationbarBackGroundImage"] forBarMetrics:UIBarMetricsDefault];
    
    YZEHomeUtils *yzehu = [YZEHomeUtils new];
    [yzehu requestArticleDateWithDelegate:self requestTag:2 AndID:self.ID Completion:^(id obj) {
        self.dic = obj[@"centent"];
        [self setClickViewContent];
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
}
-(void)getWebID:(NSString *)ID{
    self.ID = ID;
}
-(void)setClickViewContent{
    //导航栏下方的view
    self.underNavigationView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 15);
    self.underNavigationView.backgroundColor = [UIColor colorWithRed:248/255.0 green:248/255.0 blue:248/255.0 alpha:1];
    [self.myScrollView addSubview:self.underNavigationView];
//显示内容
//titleLable
    self.titleLable.numberOfLines = 0;
    self.titleLable.frame =CGRectMake(View_X, self.underNavigationView.frame.origin.y+self.underNavigationView.frame.size.height+15, [UIScreen mainScreen].bounds.size.width-(View_X*2),1000);
    
    NSString *titleString = self.dic[@"subtitle"];
    self.titleLable.text = titleString;
    //计算行数
    CGFloat labelHeight = [self.titleLable sizeThatFits:CGSizeMake(self.titleLable.frame.size.width, MAXFLOAT)].height;
    NSNumber *count = @((labelHeight) / self.titleLable.font.lineHeight);
    if ([count integerValue]  > 1 ) {//通过行数进行判断
        NSAttributedString *s = [self setLineSpacingWithControl:nil AndString:titleString AndLineSpacing:LineSpacing AndFont:TitleLableFont];
        self.titleLable.attributedText = s;
    }
    [self.titleLable sizeToFit];
    
    [self.myScrollView addSubview:self.titleLable];
//dateLable
    self.dateLable.frame = CGRectMake(View_X, self.titleLable.frame.origin.y+self.titleLable.frame.size.height+9, [UIScreen mainScreen].bounds.size.width-(View_X*2), 15);
    self.dateLable.font = [UIFont systemFontOfSize:12];
    self.dateLable.text = self.dic[@"createdDate"];
    [self.myScrollView addSubview:self.dateLable];
//imgView
//    self.imgView.frame = CGRectMake(View_X, self.dateLable.frame.origin.y+self.dateLable.frame.size.height+15, ([UIScreen mainScreen].bounds.size.width-View_X*2), ([UIScreen mainScreen].bounds.size.width-View_X*2)*636/1122);
//    [self.imgView sd_setImageWithURL:self.dic[@"uri"]];
//    [self.myScrollView addSubview:self.imgView];
//webView
    NSString *contentString = self.dic[@"content"];
    self.contentWebView.frame = CGRectMake(View_X, self.dateLable.frame.origin.y+self.dateLable.frame.size.height+15, SCREEN_WIDTH-(View_X*2),10000);
    self.contentWebView.delegate = self;
    self.contentWebView.scrollView.scrollEnabled = NO;
    self.contentWebView.backgroundColor = [UIColor whiteColor];
    [self.contentWebView sizeToFit];
//    NSString * htmlStyle = @" <style type=\"text/css\"> img{ width: 100%; height: auto; display: block; } </style> ";
    NSString * htmlcontent = [NSString stringWithFormat:@"<div id=\"webview_content_wrapper\">%@</div>", contentString];
    NSString *body = @"<body width=%f style=/word-wrap:break-word; font-family:Arial/>";
    body = [NSString stringWithFormat:body,SCREEN_WIDTH - View_X*2];
    body = [body stringByAppendingString:htmlcontent];
    [self.contentWebView loadHTMLString:body baseURL:nil];
    [self.myScrollView addSubview:self.contentWebView];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *js = @"function imgAutoFit() { \
    var imgs = document.getElementsByTagName('img'); \
    for (var i = 0; i < imgs.length; ++i) {\
    var img = imgs[i];   \
    img.style.maxWidth = %f;   \
    } \
    }";
    js = [NSString stringWithFormat:js, SCREEN_WIDTH-(View_X*2)];

    [webView stringByEvaluatingJavaScriptFromString:js];
    [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
    //获取页面高度（像素）
    NSString * clientheight_str = [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];
    float clientheight = [clientheight_str floatValue];
    //设置到WebView上
    webView.frame = CGRectMake(View_X, self.dateLable.frame.origin.y+self.dateLable.frame.size.height+15, SCREEN_WIDTH-(View_X*2), clientheight);
    //获取WebView最佳尺寸（点）
    CGSize frame = [webView sizeThatFits:webView.frame.size];
    
    //获取内容实际高度（像素）
    NSString * height_str= [webView stringByEvaluatingJavaScriptFromString: @"document.getElementById('webview_content_wrapper').offsetHeight + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-top'))  + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-bottom'))"];
    float height = [height_str floatValue];
    //内容实际高度（像素）* 点和像素的比
    height = height * frame.height / clientheight;
    //再次设置WebView高度（点）
    webView.frame = CGRectMake(13, self.dateLable.frame.origin.y+self.dateLable.frame.size.height+15, SCREEN_WIDTH-(13*2), height);
    
    //设置scrollViewContentSize
    self.myScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, webView.frame.origin.y+webView.frame.size.height + 100);

}
//设置字体间距
-(NSAttributedString *)setLineSpacingWithControl:(UITextView*)textView AndString:(NSString *)string AndLineSpacing:(CGFloat)lineSpacing AndFont:(CGFloat)font{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;// 字体的行间距
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont systemFontOfSize:font],
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    return [[NSAttributedString alloc] initWithString:string attributes:attributes];
}
-(void)setTitleViewAlignment{
    //设置右边的Item
    UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:@"收藏" style:UIBarButtonItemStylePlain target:self action:@selector(favAction)];
    self.navigationItem.rightBarButtonItem = btn;
    
    //设置左边的Item
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, LeftItemLength, 20)];
    self.navigationItem.leftBarButtonItems = @[[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"返回"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)],[[UIBarButtonItem alloc]initWithCustomView:view1]];
}
- (void)backAction{
    if (!self.isPresented) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)favAction{
    NSMutableDictionary *article = [NSMutableDictionary dictionary];
    [article setValue:self.ID forKey:@"articleId"];
    [[YZENetwork sharedInstace]postRequestWithUrl:[BASE stringByAppendingString:URL_Fav] parameters:article delegate:self requestTag:1 successBlock:^(id responseObject) {
        [QMUITips showSucceed:@"收藏成功！" inView:self.myScrollView hideAfterDelay:2];
    }];
}
@end
